package com.zhou.cloud.config;

import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.util.ResourceUtils;

/**
 * @descrition: es配置
 * @author: zhouyongjun
 * @date: 2022/9/7
 **/
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.zhou.cloud.repositories")
@PropertySource(value = "classpath:es.properties")
@Getter
@Setter
public class EsConfig {
    @Value("${elasticsearch.host}")
    String host;
    @Value("${elasticsearch.port}")
    int port;
    @Value("${elasticsearch.user}")
    private String user;
    @Value("${elasticsearch.password}")
    private String password;

   /* @Bean(name="esClient")
    public TransportClient getClient() {

        return null;
    }*/

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = null;

        try {
            /** 用户认证对象 */
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            /** 设置账号密码 */
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(user, password));
            /** 创建rest client对象 */
            RestClientBuilder builder = RestClient.builder(new HttpHost(host, port))
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(
                                HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    });
            client = new RestHighLevelClient(builder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return client;
    }


}
